import { defineStore } from "pinia";
import Blank from "@/components/Layout/blank.vue";
import { menuRouteJSON } from "@/router/menuRoute.js";

const modules = import.meta.glob("/src/views/**/*");
import router from "@/router";
const addRouteMenu = (menu) => {
  if (menu.children && menu.children.length > 0) {
    menu.children.forEach((child) => {
      router.addRoute(menu.name, {
        path: child.path,
        name: child.name,
        meta: { hidden: child.hidden, label: child.label },
        redirect: child.redirect,
        component: child.component
          ? modules[`/src/views/${child.component}`]
          : "",
      });
      addRouteMenu(child);
    });
  }
};

export const useMenuStore = defineStore("menu", {
  state: () => {
    return {
      menuRouters: JSON.parse(sessionStorage.getItem("routers")) || [], //menuRouteJSON || []
    };
  },
  actions: {
    initRouteMenu() {
      router.addRoute("Index", {
        path: "/hello",
        name: "Hello",
        component: modules[`/src/views/Home/hello.vue`],
      });
      router.addRoute("Index", {
        path: "/:pathMatch(.*)",
        name: "bad-not-found",
        component: modules[`/src/views/notFound.vue`],
      });
      this.menuRouters.forEach((menu) => {
        router.addRoute("Index", {
          path: menu.path,
          name: menu.name,
          meta: menu.meta,
          redirect: menu.redirect,
          component: menu.component
            ? modules[`/src/views/${menu.component}`]
            : Blank,
        });
        addRouteMenu(menu);
      });
    },
    setRouters(val) {
      this.menuRouters = val;
      sessionStorage.setItem(`routers`, JSON.stringify(val));
    },
    removerouters() {
      this.menuRouters = [];
      sessionStorage.removeItem(`routers`);
    },
  },
});
